package com.example.xlzx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.xlzx.entity.Consultation;
import com.example.xlzx.dao.ConsultationMapper;
import com.example.xlzx.service.IConsultationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 心理医生咨询表 服务实现类
 * </p>
 *
 * @author 1
 * @since 2025-03-07
 */
@Service
public class ConsultationServiceImpl extends ServiceImpl<ConsultationMapper, Consultation> implements IConsultationService {
    @Autowired
    private ConsultationMapper chatMessageMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String CHAT_PREFIX = "chat:";

    /**
     * 发送消息
     */
    public void sendMessage(Consultation message) {
        // 存储到数据库
        chatMessageMapper.insert(message);

        // 存储到 Redis（用于实时推送）
        String key = CHAT_PREFIX + message.getSenderId() + ":" + message.getReceiverId();
        redisTemplate.opsForList().leftPush(key, message.getContent());
    }

    /**
     * 获取聊天记录
     */
    public List<Consultation> getChatHistory(Long senderId, Long receiverId) {
        QueryWrapper<Consultation> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq("sender_id", senderId)
                .eq("receiver_id", receiverId)
                .or()
                .eq("sender_id", receiverId)
                .eq("receiver_id", senderId)
                .orderByDesc("create_time");
        return chatMessageMapper.selectList(queryWrapper);
    }

    /**
     * 获取实时消息
     */
    public List<String> getRealTimeMessages(Long senderId, Long receiverId) {
        String key = CHAT_PREFIX + senderId + ":" + receiverId;
        return redisTemplate.opsForList().range(key, 0, -1);
    }
}
